#### Measuring support for liberal democracy
#### Code for revised draft of paper
#### Britain
#### Version 5 

library(tidyverse)
library(psych)
library(lavaan)
library(car)
library(semTable)
library(psychTools)
library(tth)
library(RColorBrewer)
library(lubridate)
library(matrixStats)

# read data
sd_dat = read.csv("supdem_GB_2.csv")

# select and rename items
sd17 = sd_dat[, c("uk_frexp1", "uk_frexp2", "uk_frassc1", "uk_frassc2", "uk_frassc3", "uk_unisuff1", "uk_unisuff2",
                  "uk_decelec1", "uk_decelec2", "uk_frelect1", "uk_frelect2", "uk_judcnstr1", "uk_judcnstr2", 
                  "uk_legcnstr1", "uk_legcnstr2", "uk_eqlaw1", "uk_eqlaw2")]
names(sd17) = c("FREXP1", "FREXP2", "FRASSC1", "FRASSC2", "FRASSC3", "UNISUFF1", "UNISUFF2", 
                "DECELEC1", "DECELEC2", "FRELECT1", "FRELECT2", "JUDCNSTR1", "JUDCNSTR2", 
                "LEGCNSTR1", "LEGCNSTR2", "EQLAW1", "EQLAW2")

## Plot item distributions

# colour palettes
lik5 = c(brewer.pal(5, "BrBG"), "#b4b1b1")
lik5_labs = c("StrAg", "SomeAg", "Neither", "SomeDis",
              "StrDis", "DK")
qual5 = c(brewer.pal(5, "Dark2"), "#b4b1b1")

# recode NAs
sd_plot = as.data.frame(sapply(sd17, function(x) car::recode(x, "999=NA"), simplify = TRUE))

# plot
pdf("supdem_distr_britain.pdf", height=8, width=6)
par(mfrow=c(5, 4), mar=c(3, 2, 0.5, 0.5), tcl=-0.2, cex=0.9, las=2, mgp=c(1.8, 0.9, 0))
for(i in 1:length(sd_plot)) {
  barplot(height = table(sd_plot[, names(sd_plot)[i]]) / dim(sd_plot)[1] * 100, names.arg=lik5_labs, 
          axes=FALSE, col=lik5, cex.names=0.7, mgp=c(1, 0.2, 0), ylim=c(0, 80))
  axis(side=2, labels=TRUE, cex.axis=0.7, mgp=c(1, 0.4, 0))
  text(x=1.5, y=75, names(sd_plot)[i], cex=0.8, adj=0)
}
dev.off()

# recode to orient all items in a pro-democratic direction and DKs as "neither"
sd_dat_r = sd17
dem_vnam = c("FREXP1", "FRASSC2", "UNISUFF2", "DECELEC2", "FRELECT1", "JUDCNSTR1", "LEGCNSTR2", "EQLAW2")
aut_vnam = c("FREXP2", "FRASSC1", "FRASSC3", "UNISUFF1", "DECELEC1", "FRELECT2", "JUDCNSTR2", "LEGCNSTR1", "EQLAW1")
sd_dat_r[, dem_vnam] = lapply(sd_dat_r[, dem_vnam], car::Recode, "1=5; 2=4; 3=3; 4=2; 5=1; 99=3")
sd_dat_r[, aut_vnam] = lapply(sd_dat_r[, aut_vnam], car::Recode, "1=1; 2=2; 3=3; 4=4; 5=5; 99=3")
sd_dat = cbind(sd_dat, sd_dat_r)

## Reliability and dimensionality

# alpha
sd_cor = cor(sd_dat_r, use="pair")
psych::alpha(sd_cor)
alph_out <- psych::alpha(sd_cor)
write.csv(alph_out[[1]], file="sd_alpha.csv")

# eigenvalues of principal components
eigen(sd_cor)$values
write.csv(eigen(sd_cor)$values, file="sd_eigen.csv")

# 1-factor EFA
psych::fa(sd_dat_r, nfactors=1)
efa1 = psych::fa(sd_dat_r, nfactors=1)
efa_html = tth(fa2latex(efa1))
writeLines(efa_html, "sd_efa1.html")

# ordinal
sd_pcor = polychoric(sd_dat_r)$rho
write.csv(sd_pcor, "sd_pcormat.csv", row.names=TRUE)
psych::fa(sd_pcor, nfactors=1, n.obs=dim(sd_dat)[1])
efa_ord = psych::fa(sd_pcor, nfactors=1, n.obs=dim(sd_dat)[1])
efa_ord_html = tth(fa2latex(efa_ord))
writeLines(efa_ord_html, "sd_efa1_ord.html")


## cfa models

# liberal democracy factor with orthogonal methods factor

cfa_mod_1 = '
SupLD =~ FREXP1 + FREXP2 + FRASSC1 + FRASSC2 + FRASSC3 + UNISUFF1 + UNISUFF2 
          + DECELEC1 + DECELEC2 + FRELECT1 + FRELECT2 + JUDCNSTR1 + JUDCNSTR2 
          + LEGCNSTR1 + LEGCNSTR2 + EQLAW1 + EQLAW2
PosVal =~ FREXP1 + FRASSC2 + UNISUFF2 + DECELEC2 + FRELECT1 + JUDCNSTR1 + LEGCNSTR2 + EQLAW2
'
sd_cfa_1 = cfa(cfa_mod_1, data=sd_dat, estimator="MLR", orthogonal=TRUE, std.lv=TRUE,
               sampling.weights="W8")
summary(sd_cfa_1, fit.measures=TRUE)
semTable(sd_cfa_1, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_1fac_std_table_w.html")
sd_cfa_1_std_fit = fitMeasures(sd_cfa_1, output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_1_std_fit, file = "cfa_1fac_std_fit_w.csv", row.names = TRUE)

# liberal democracy factor with orthogonal methods factor, ordinal

sd_cfa_1_std = cfa(cfa_mod_1, data=sd_dat, estimator="WLSMV", orthogonal=TRUE, ordered=TRUE, 
                   std.lv=TRUE)
summary(sd_cfa_1_std, fit.measures=TRUE)
semTable(sd_cfa_1_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"), 
         type="html", file="cfa_1fac_ord_std_table.html")
sd_cfa_1_std_fit = fitMeasures(sd_cfa_1_std,  output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_1_std_fit, file = "cfa_1fac_std_ord_fit.csv", row.names = TRUE)

# electoral democracy and rule of laws factors with orthogonal methods factor

cfa_mod_2 = '
SupED =~ FREXP1 + FREXP2 + FRASSC1 + FRASSC2 + FRASSC3 + UNISUFF1 + UNISUFF2 
          + DECELEC1 + DECELEC2 + FRELECT1 + FRELECT2
SupRL =~ JUDCNSTR1 + JUDCNSTR2 + LEGCNSTR1 + LEGCNSTR2 + EQLAW1 + EQLAW2
PosVal =~ FREXP1 + FRASSC2 + UNISUFF2 + DECELEC2 + FRELECT1 + JUDCNSTR1 + LEGCNSTR2 + EQLAW2
PosVal ~~ 0*SupED
PosVal ~~ 0*SupRL
'
sd_cfa_2_std = cfa(cfa_mod_2, data=sd_dat, estimator="MLR", std.lv=TRUE, sampling.weights="W8")
semTable(sd_cfa_2_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_2fac_std_table_w.html")
sd_cfa_2_std_fit = fitMeasures(sd_cfa_2_std, output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_2_std_fit, file = "cfa_2fac_std_fit_w.csv", row.names = TRUE)

# electoral democracy and rule of laws factors with orthogonal methods factor, ordinal

sd_cfa_2_std = cfa(cfa_mod_2, data=sd_dat, estimator="WLSMV", ordered=TRUE, std.lv=TRUE)
summary(sd_cfa_2_std, fit.measures=TRUE)
semTable(sd_cfa_2_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"), 
         type="html", file="cfa_2fac_ord_std_table.html")
sd_cfa_2_std_fit = fitMeasures(sd_cfa_2_std,  output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_2_std_fit, file = "cfa_2fac_std_ord_fit.csv", row.names = TRUE)

# lr test - 1 v 2-fac models

lavTestLRT(sd_cfa_1_std, sd_cfa_2_std, method = "satorra.bentler.2010")
write.csv(lavTestLRT(sd_cfa_2_std, sd_cfa_1_std, method = "satorra.bentler.2010"), 
          file = "lrtest_cfas.csv", row.names = TRUE)


## Trimmed 7-item scale
 
sd_dat_7 = sd_dat_r[, c("FREXP2", "FRASSC1", "UNISUFF1", "FRELECT2", "JUDCNSTR2", "LEGCNSTR1", "EQLAW1")]
 
# additive scale
sd_dat$SUPDEM_7IT = rowMeans(sd_dat_7, na.rm=TRUE)

# 1-factor CFA

cfa_mod_7i = 'SupLD =~ FREXP2 + FRASSC1 + UNISUFF1 + FRELECT2 + JUDCNSTR2 + LEGCNSTR1 + EQLAW1'

sd_cfa_7i_std = cfa(cfa_mod_7i, data=sd_dat, estimator="MLR", std.lv=TRUE, sampling.weights="W8")
summary(sd_cfa_7i_std, fit.measures=TRUE)
semTable(sd_cfa_7i_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_7it_std_table_w.html")
sd_cfa_7i_fit = fitMeasures(sd_cfa_7i_std, output = "matrix",
                            fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_7i_fit, file = "cfa_7it_std_fit_w.csv", row.names = TRUE)

# 1-factor CFA, ordinal

sd_cfa_7i_ord = cfa(cfa_mod_7i, data=sd_dat_r, estimator="WLSMV", ordered=TRUE, std.lv=TRUE)
summary(sd_cfa_7i_ord, fit.measures=TRUE)
semTable(sd_cfa_7i_ord, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_7it_ord_std_table.html")
sd_cfa_7i_fit = fitMeasures(sd_cfa_7i_ord, output = "matrix",
                            fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_7i_fit, file = "cfa_7it_ord_std_fit.csv", row.names = TRUE)

# reliability
psych::alpha(sd_dat_7)
alph7_out <- psych::alpha(sd_dat_7)
write.csv(alph7_out[[1]], file="sd7_alpha.csv")

# ordinal reliability
sd7_pcor = polychoric(sd_dat_7)$rho
alph7_ord_out <- psych::alpha(sd7_pcor)
write.csv(alph7_ord_out[[1]], file="sd7_ord_alpha.csv")


## Criterion variables

# 1. Linz democratic support (3 statements): core_sup_1
# 2. Churchill democratic support "Democracy may have problems"
# 3. Strong leader item: uk_strglead
# 4. Importance of democracy item
# 5. Satisfaction with democracy: core_sat_1
# 6. Government/executive approval
# 7. Left-right / lib-cons ideology: core_pos_9
# 8. Populist attitudes scale: core_pop_1 - core_pop_3
# 9. Political trust scale: core_plt_1_1 - core_plt_1_4

## recode criterion variables

# linz question: recode such that support democ = 3, support auth = 1. 
table(sd_dat$core_sup_1, useNA="ifany")
sd_dat$LINZ_SUPDEM = car::recode(sd_dat$core_sup_1, "1=3; 3=2; 2=1; 99=NA")

# strong leaders question; recode such that support is high, oppose is low
table(sd_dat$uk_strglead, useNA="ifany")
sd_dat$STRONG_LEAD = car::recode(sd_dat$uk_strglead, "1=5; 2=4; 3=3; 4=2; 5=1; 99=3")

# satisfaction with democracy; recode such that satisfaction = high
table(sd_dat$core_sat_1, useNA="ifany")
sd_dat$SATIS_DEM = car::recode(sd_dat$core_sat_1, "99=NA")

# left-right (or equiv) ideology; recode such that right / conservative = high
table(sd_dat$core_pos_9, useNA="ifany")
sd_dat$LR_IDEOL = car::recode(sd_dat$core_pos_9, "12=NA")

# political trust; recode each item such that trust is high
table(sd_dat$core_plt_1_1, useNA="ifany")
sd_dat$trust_govt = car::recode(sd_dat$core_plt_1_1, "12=NA")

table(sd_dat$core_plt_1_2, useNA="ifany")
sd_dat$trust_parl = car::recode(sd_dat$core_plt_1_2, "12=NA")

table(sd_dat$core_plt_1_3, useNA="ifany")
sd_dat$trust_legsys = car::recode(sd_dat$core_plt_1_3, "12=NA")

table(sd_dat$core_plt_1_4, useNA="ifany")
sd_dat$trust_pol = car::recode(sd_dat$core_plt_1_4, "12=NA")

psych::alpha(sd_dat[, c("trust_govt", "trust_parl", "trust_legsys", "trust_pol")])
sd_dat$POL_TRUST = rowMeans(sd_dat[, c("trust_govt", "trust_parl", "trust_legsys", "trust_pol")])

# populism; recode each item such that trust is high
table(sd_dat$core_pop_1, useNA="ifany")
sd_dat$pop1 = car::recode(sd_dat$core_pop_1, "1=5; 2=4; 3=3; 4=2; 5=1; 99=3")
sd_dat$pop2 = car::recode(sd_dat$core_pop_2, "1=5; 2=4; 3=3; 4=2; 5=1; 99=3")
sd_dat$pop3 = car::recode(sd_dat$core_pop_3, "1=5; 2=4; 3=3; 4=2; 5=1; 99=3")
psych::alpha(sd_dat[, c("pop1", "pop2", "pop3")])
sd_dat$POP_ATT = sd_dat$pop1

## correlations

mixedCor(sd_dat[, c("SUPDEM_7IT", "LINZ_SUPDEM", "STRONG_LEAD", "SATIS_DEM", "LR_IDEOL", "POL_TRUST", "POP_ATT")])$rho
crit_cor = mixedCor(sd_dat[, c("SUPDEM_7IT", "LINZ_SUPDEM", "STRONG_LEAD", "SATIS_DEM", "LR_IDEOL", "POL_TRUST", "POP_ATT")])$rho
write.csv(crit_cor, file="sd7_crit_cormat.csv", row.names=TRUE)
